package com.ruiysoft.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruiysoft.pub.core.ResultCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by 化增光 on 2018/5/22.
 */
@Component("customOAuth2AccessDeniedHandler")
public class CustomOAuth2AccessDeniedHandler extends OAuth2AccessDeniedHandler {

    private static Logger logger = LoggerFactory.getLogger(CustomOAuth2AccessDeniedHandler.class);

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException authException) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        Map map = new HashMap();
        map.put("success", false);
        map.put("message", authException.getMessage());
        map.put("bizCode", ResultCode.CODE_COMMON_ERROR);
        response.setContentType("application/json");
        response.setStatus(HttpServletResponse.SC_OK);
        response.getWriter().write(objectMapper.writeValueAsString(map));
        logger.debug("denied access {}",authException);
    }
}
